package threadexercise;

import java.util.concurrent.Semaphore;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-11-16
 * Time：21:24
 */
public class Demo1 {
    static int sum = 0;
    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(1);
        Thread t1 = new Thread(() -> {
            try {
                for (int i = 0; i < 10000; i++) {
                    semaphore.acquire();
                    sum++;
                    semaphore.release();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread t2 = new Thread(() -> {
            try {
                for (int i = 0; i < 10000; i++) {
                    semaphore.acquire();
                    sum++;
                    semaphore.release();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(sum);
    }

}
